package com.dawnling.countdownlistdemo.ui;

import android.os.Bundle;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;

import com.dawnling.countdownlistdemo.R;
import com.dawnling.countdownlistdemo.app.MyApplication;
import com.dawnling.countdownlistdemo.base.BaseActivity;
import com.dawnling.countdownlistdemo.utils.MyTimer;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

public class MainActivity extends BaseActivity implements MyTimer.Listener {

    //加入倒计时的数据集合
    private Map<Integer, OrderBean> map = new HashMap<Integer, OrderBean>();
    private RecyclerView mRecyclerView;
    private OrderAdater mAdapter;
    private List<OrderBean> list = new ArrayList<>();

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        initData();
        mRecyclerView = findViewById(R.id.recyclerView);
        mRecyclerView.setLayoutManager(new LinearLayoutManager(this));
        mAdapter = new OrderAdater();
        mRecyclerView.setAdapter(mAdapter);
        mAdapter.setNewData(list);
    }

    private void initData() {
        list.clear();
        map.clear();
        list.add(new OrderBean(1, 100));
        list.add(new OrderBean(2, 200));
        list.add(new OrderBean(3, 50033330));
        list.add(new OrderBean(4, -1));
        list.add(new OrderBean(5, 0));
        list.add(new OrderBean(6, 100033330));
        for (int i = 0; i < list.size(); i++) {
            if (list.get(i).delivery_countdown_time > 0) map.put(list.get(i).id, list.get(i));
        }
    }

    @Override
    protected void onStart() {
        MyApplication.getInstance().getTimer().add(this);
        super.onStart();
    }

    @Override
    protected void onStop() {
        MyApplication.getInstance().getTimer().remove(this);
        super.onStop();
    }

    @Override
    public void onNextSecond() {
        Iterator<Map.Entry<Integer, OrderBean>> entries = map.entrySet().iterator();
        while (entries.hasNext()) {
            Map.Entry<Integer, OrderBean> entry = entries.next();
            OrderBean value = entry.getValue();
            value.onReducePay();
            if (missTime > 0L) {
                value.onReducePay(missTime);
            }
        }
        missTime = 0;
        mHandler.post(new Runnable() {
            @Override
            public void run() {
                mAdapter.onNextSecond();
            }
        });
    }
}
